﻿$(document).ready(Page_Load);

var rowdata;
var currentId;

var currentRole;

function Page_Load(e) {
    LoadGrid();

    $('.button').button();

    $('[name="btnAdd"]').click(function () {
        $("#dialog-newrole").dialog({
            resizable: false,
            height: 225,
            width: 360,
            modal: true,
            buttons: {
                'Create': function () {
                    CreateRole();
                    $(this).dialog('close');
                },
                'Cancel': function () {
                    $(this).dialog('close');
                }
            },
            close: function () {
                $("#new-role").val("");

                $("#error-container").removeClass("ui-state-error ui-corner-all");
                $("#error").html("");

                $('input').removeClass("ui-state-error");
            }
        });
    });

    $('[name="btnUpdate"]').click(function () {
        GetUsers();
        GetRoles();

        $("#dialog-addtorole").dialog({
            resizable: false,
            height: 225,
            width: 360,
            modal: true,
            buttons: {
                'Add': function () {
                    AddToRole();
                    $(this).dialog('close');
                },
                'Cancel': function () {
                    $(this).dialog('close');
                }
            },
            close: function () {

                $("#error-container").removeClass("ui-state-error ui-corner-all");
                $("#error").html("");

                $('input').removeClass("ui-state-error");
            }
        });
    });

}

function LoadGrid() {

    $("#list2").jqGrid(
        {
            datatype: "local",
            colNames: ['', 'Role', 'Users', ''],
            colModel: [
                { name: 'act', index: 'act2', width: 38, sortable: false },
                { name: 'id', index: 'id', width: 250, editable: false },
   		        { name: 'UsersInRole', index: 'UsersInRole', width: 50, editable: false, align: 'center' },
                { name: 'act2', index: 'act2', width: 38, sortable: false }
            ],
            rowNum: 10,
            pager: '#pager2',
            sortname: 'id',
            viewrecords: true,
            sortorder: "id",
            caption: "Roles",
            height: 250,
            width: "100%",
            editurl: 'somepage.aspx',
            gridComplete: function () {
                var ids = $("#list2").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];
//                    lock = "<img class=\'gridaction\' src=\'/Images/Encrypt.png\' alt=\'Lock or Unlock\' title=\'Lock or Unlock\' onclick=\"UnlockUser('" + cl + "');\"/>";
//                    activate = "<img class=\'gridaction\' src=\'/Images/base_checkmark_32.png\' alt=\'Activate\' title=\'Activate\' onclick=\"ApproveUser('" + cl + "');\"/>";
                    ed = "<img class=\'gridaction\' src=\'/Images/Users.png\' alt=\'Remove a User From Role\' title=\'Remove a User From Role\' onclick=\"RemoveUser('" + cl + "');\"/>";
                    de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteRole('" + cl + "');\"/>";
                    $("#list2").jqGrid('setRowData', ids[i], { act: ed, act2: de });
                }
            }
        });

        $("#list2").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false, beforeRefresh: function () { GetRoles(); } })

        GetRoles();
}

function GetRoles() {

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Roles.aspx/GetAllRoles",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: LoadRoleStats_Success,
                error: LoadRoleStats_Error
            });

}


function LoadRoleStats_Success(data, textStatus, XMLHttpRequest) {
    rowdata = data.d;
    BindGrid($("#list2"), rowdata, "RoleName", 1);

    var options = $("#roles");

    options.children().remove();
    options.append("<option />");

    $.each(rowdata, function (i, item) {
        options.append($("<option />").val(item["RoleName"]).text(item["RoleName"]));
    });
}

function LoadRoleStats_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadRoleStats", 100);
    alert("An error occurred loading the role statistics. Error: " + XMLHttpRequest);

}

function CreateRole() {
    var rolename = $('#new-role');

    var webMethodParams = JSON.stringify({ RoleName: rolename.val() });

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Roles.aspx/CreateRole",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}

function RefreshGrid(data, textStatus, XMLHttpRequest) {
    GetRoles();
}

function Command_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadRoleStats", 100);
    alert("An error occurred loading the role statistics. Error: " + XMLHttpRequest);

}

function DeleteRole(role) {
    var roledata = $("#list2").jqGrid('getRowData', role);

    if (roledata["id"] != "Administrator") {
        var $dialog = $('<div></div>')
		.html('Please confirm the delete request (' + roledata["id"] + ').')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    buttons: {
		        'Yes': function () {
		            DeleteConfirmed(role);
		            $(this).dialog('close');
		        },
		        'No': function () {
		            $(this).dialog('close');
		        }
		    },
		    title: 'Confirm Delete'
		});
        $dialog.dialog('open');
    }
    else {
        DisplayAdminLockdownMessage();
    }
}


function DeleteConfirmed(role) {
    var webMethodParams = JSON.stringify({ RoleName: role });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Roles.aspx/DeleteRole",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}


function DisplayAdminLockdownMessage() {
    var $dialog = $('<div></div>')
		.html('Unable to modify the default administrator group.')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    title: 'Error'
		});
    $dialog.dialog('open');

}


function GetUsers() {

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Users.aspx/GetAllUsers",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: LoadUserStats_Success,
                error: LoadUserStats_Error
            });

}


function LoadUserStats_Success(data, textStatus, XMLHttpRequest) {
    var userdata = data.d;
    var options = $("#users");

    options.children().remove();
    options.append("<option />");

    $.each(userdata, function (i, item) {
        options.append($("<option />").val(item["UserId"]).text(item["UserName"]));
    });
}


function LoadUserStats_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadUserStats", 100);
    alert("An error occurred loading the user statistics. Error: " + XMLHttpRequest);

}

function AddToRole() {
    var user = $("#users").val();
    var role = $("#roles").val();

    var webMethodParams = JSON.stringify({ RoleName: role, UserId: user });

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Roles.aspx/AddToRole",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}

function RemoveUser(role) {
    
    currentRole = role;

    var webMethodParams = JSON.stringify({ RoleName: role });

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Roles.aspx/UsersInRole",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: UsersInRole_Success,
                error: Command_Error
            });
}

function UsersInRole_Success(data, textStatus, XMLHttpRequest) {
    var userdata = data.d;
    var options = $("#usersinrole");

    options.children().remove();
    options.append("<option />");

    $.each(userdata, function (i, item) {
        options.append($("<option />").val(item["UserId"]).text(item["UserName"]));
    });

    $("#dialog-removeuser").dialog({
            resizable: false,
            height: 225,
            width: 360,
            modal: true,
            buttons: {
                'Remove': function () {
                    RemoveFromRole();
                    $(this).dialog('close');
                },
                'Cancel': function () {
                    $(this).dialog('close');
                }
            },
            close: function () {

                $("#error-container").removeClass("ui-state-error ui-corner-all");
                $("#error").html("");

                $('input').removeClass("ui-state-error");
            }
        });

}

function RemoveFromRole()
{
    var user = $("#usersinrole").val();

    var webMethodParams = JSON.stringify({ RoleName: currentRole, UserId: user });

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Roles.aspx/RemoveFromRole",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshGrid,
                error: Command_Error
            });
}